import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { SettingsService, ALAIN_I18N_TOKEN, TitleService, User } from '@delon/theme';
import { ACLService } from '@delon/acl';
import { NzIconService } from 'ng-zorro-antd';

import { ICONS_AUTO } from '../../../style-icons-auto';
import { ICONS } from '../../../style-icons';

import { I18NService } from '@core/i18n/i18n.service';
import { UserService } from '@core/user/user.service';

/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
  constructor(
    iconSrv: NzIconService,
    private settingService: SettingsService,
    private aclService: ACLService,
    private httpClient: HttpClient,
    private userService: UserService,
    @Inject(DOCUMENT) private doc: any,
    @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
    private titleSrv: TitleService,
  ) {
    iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
  }

  load(): Promise<any> {
    const isLogined = this.userService.isLogin;

    const api = [
      this.httpClient.get(`assets/i18n/${this.i18n.currentLang}.json`),
      this.httpClient.get(`assets/app-data.json`),
    ];
    if (isLogined) {
      // 个人信息
      api.push(this.httpClient.get('/cf/admin/user/info'));
    }

    return new Promise(resolve => {
      zip(...api)
        .pipe(
          // 接收其他拦截器后产生的异常消息
          catchError(([langData, appData, userInfo]) => {
            resolve(null);
            return [langData, appData, userInfo];
          }),
        )
        .subscribe(
          ([langData, appData, userInfo]) => {
            if (isLogined && userInfo) {
              // 用户信息：包括姓名、头像
              const userData: User = {
                userId: userInfo.data.user.userId,
                username: userInfo.data.user.username,
                name: userInfo.data.user.name,
                avatar: userInfo.data.user.avatar,
                roles: userInfo.data.roles,
                permissions: this.setState(userInfo.data.permissions),
              };
              this.settingService.setUser(userData);
            }

            // Load general language data
            this.i18n.load(this.i18n.currentLang, langData);

            // application data
            const res: any = appData;
            // 应用信息：包括站点名、描述、年份
            this.settingService.setApp(res.app);

            // ACL：设置权限为全量
            this.aclService.setFull(true);
            // 设置标题
            this.titleSrv.default = '';
            this.titleSrv.suffix = '雅瑞中台系统';
          },
          () => {},
          () => {
            resolve(null);
            this.removeLoading();
          },
        );
    });
  }

  private removeLoading() {
    const el = this.doc.querySelector('#j-preloader');

    if (el) {
      el.remove();
    }
  }

  private setState(permissions = []) {
    const list = {};
    for (const i of permissions) {
      list[i] = true;
    }
    return list;
  }
}
